# Copyright (C) Nicola Bizzoca   2006/2007  <hannibal_smith@users.sourceforge.net>
# Copyright (C) Simone Economo   2006/2007  <ekoes@users.sourceforge.net>
# 
#    This file is part of Absynth-FTP.
#
#    Absynth-FTP is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Absynth-FTP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import gtk, gobject
#import conf
#from engine import Widgets

class genericTreeView:
    
    def createTree(self, type, properties):
        self.widget = gtk.TreeView()
        self.__properties, self.__type = properties, type
        
    def setColumns(self, headers):  
          
        methods = {
            "col-visible"    : "set_visible",
            "col-resizable"  : "set_resizable",
            "col-min-width"  : "set_min_width",
            "col-size-mode"  : "set_sizing",
            "col-fixed-width": "set_fixed_width",
        }
        contents = {
            "image"    : "CellRendererPixbuf",
            "text"     : "CellRendererText",
            "progress" : "CellRendererProgress",
        }

        types = []
        for values in headers:
            """if values[1] == "image":
                columnType = gtk.gdk.Pixbuf
            else:
                columnType = values[2]"""
            columnType = values[2]  
            types.append(columnType)
        self.store = getattr(gtk, "%sStore" % self.__type)(*types)
        self.widget.set_model(self.store)
        
        self.columns, self.rows, self.iters, self.renderers, position = [], [], [], [], 0
        for values in headers:
            currentColumnRenderer = getattr(gtk, contents[values[1]])()
            currentColumn = gtk.TreeViewColumn(values[0], currentColumnRenderer)
            if values[1] == "image":
                currentColumn.set_attributes(currentColumnRenderer, icon_name = position)
            elif values[1] == "text":
                currentColumn.set_attributes(currentColumnRenderer, text = position)
            elif values[1] == "progress":
                currentColumn.set_attributes(currentColumnRenderer, value = position)
            getattr(currentColumn, methods["col-visible"])(values[3])
            getattr(currentColumn, methods["col-resizable"])(values[4])
            
            try:
                if values[4] is True:
                    getattr(currentColumn, methods["col-min-width"])(values[5])
                else:
                    if values[5] is None: raise
                    
                    getattr(currentColumn, methods["col-size-mode"])(gtk.TREE_VIEW_COLUMN_FIXED)
                    getattr(currentColumn, methods["col-fixed-width"])(values[5])
            except: getattr(currentColumn, methods["col-size-mode"])(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
                
            try:
                if type(values[6]) is int:
                    self.columns[values[6]].pack_start(currentColumnRenderer)
                    if values[1] == "image":
                        self.columns[values[6]].set_attributes(currentColumnRenderer, icon_name = position)
                    elif values[1] == "text":
                        self.columns[values[6]].set_attributes(currentColumnRenderer, text = position)
            except: pass
                
            self.widget.append_column(currentColumn)
            self.columns.append(currentColumn)
            self.renderers.append(currentColumnRenderer)
            position += 1
            
        self.__setProperties()
        self.__setSortId(0)
            
    def __setProperties(self):
        
        methods = {
            "headers-visible"  : "set_headers_visible",
            "headers-clickable": "set_headers_clickable",
            "rows-search"      : "set_enable_search",
            "rows-same-height" : "set_fixed_height_mode",
            "rows-alternate"   : "set_rules_hint",
            "rows-reorder"     : "set_reorderable",
        }
        
        for property, value in self.__properties.items():
            getattr(self.widget, methods[property])(value)
            #print methods[property].replace("set", "get"), getattr(self.widget, methods[property].replace("set", "get"))()
            
    def addListRow(self, data, position = None):
        if self.__type == "Tree": return
        
        if position is None:
            self.iters.append(self.store.append(data))
        else:
            self.iters.append(self.store.insert(position, data))
        self.__updateRows()
        
    def addTreeRow(self, data, parent = None, position = None):
        if self.__type == "List": return
        
        try:
            parent = self.iters[parent]
        except:
            parent = None
            
        if position is None:
            self.iters.append(self.store.append(parent, data))
        else:
            self.iters.append(self.store.insert(parent, position, data))
        self.__updateRows()
        
    def clearRows(self):
        self.store.clear()
            
    def __updateRows(self):
        self.rows = list(self.store)
        
    def getFlatRowDatas(self):
        data = []
        for row in self.rows:
            data.append(list(row))
        return data
    
    def __setSortId(self, start = None):
        methods = {
            "col-sort-id":    "set_sort_column_id",
        }
        if start is None:
            start = 0
        for currentColumn in self.columns:
            getattr(currentColumn, methods["col-sort-id"])(start)
            start += 1

class testSuite:
    
    def __init__(self):
        
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.connectEvents(self.window, {
             "delete_event" : self.delete,
             "destroy": self.destroy,
        })
        
        self.tree = genericTreeView()
        self.tree.createTree("Tree", {
            "headers-visible"  : True,
            "headers-clickable": True,
            "rows-search"      : False,
            "rows-same-height" : False,
            "rows-alternate"   : True,
            "rows-reorder"     : True,
        })
        self.tree.setColumns([
            ("Filename", "image", str, True, True),
            ("Size", "text", str, True, False, 50),
            ("Last Edit", "text", str, True, True, None),
            ("Filename-hidden", "text", str, False, False, None, 0),
        ])
        self.tree.addTreeRow(["stock_folder", "4096", "aee", "usr"])
        self.tree.addTreeRow(["stock_folder", "4096", "?", "bin"], parent = 0)
        self.tree.addTreeRow(["stock_folder", "4096", "?", "etc"], parent = 0)
        self.tree.addTreeRow(["stock_folder", "4096", "?", "var"], parent = 0)
        self.tree.addTreeRow(["stock_folder", "4096", "?", "local"], parent = 0, position = 2)
        self.tree.addTreeRow(["stock_folder", "4097", "beee", "bin"])
        self.tree.renderers[0].set_property('xalign', 1.0)
        self.tree.columns[0].set_sort_column_id(3)
        
        self.window.add(self.tree.widget)
        self.tree.widget.show()
        self.window.show()
    
    def connectEvents(self, widget, events):
        for type,callback in events.items():
            widget.connect(type, callback)

    def delete(self, widget, event, data=None):
        #print "delete event occurred"
        return False

    def destroy(self, widget, data=None):
        #print "destroy signal occurred"
        gtk.main_quit()
        
    def runTest(self):
        gtk.main()
        
if __name__ == "__main__": 
    GTK = testSuite()
    GTK.runTest()